/**
 * AI生成服务 - 集成多模型功能的统一生成服务
 */

import { optimizePrompts, type PromptLayers } from '../utils/prompt-optimizer';
import { 
  validateFormatOutput
} from '../utils/format-prompt-generator';
import { 
  smartFormatConversion,
  cleanupHTML 
} from '../utils/markdown-to-html-converter';
import { 
  analyzePromptStructure,
  printPromptAnalysis,
  generatePromptChart,
  validatePromptQuality 
} from '../utils/prompt-analyzer';
import { 
  MultiModelService, 
  type ComparisonResult 
} from './multi-model-service';
import { 
  ModelType
} from './models/base-model-adapter';
import { 
  type ModelSelectionCriteria 
} from './models/model-router';

export interface GenerationRequest {
  modelConfigId?: string;  // 使用模型配置ID（可选，用于向后兼容）
  modelType?: ModelType;   // 直接指定模型类型
  prompt: string;
  parameters?: {
    temperature?: number;
    maxTokens?: number;
    topP?: number;
    frequencyPenalty?: number;
    presencePenalty?: number;
  };
  selectionCriteria?: ModelSelectionCriteria;  // 智能模型选择条件
}

export interface GenerationResponse {
  content: string;
  usage?: {
    promptTokens: number;
    completionTokens: number;
    totalTokens: number;
  };
  modelId: string;
  error?: string;
  formatValidation?: {
    isValid: boolean;
    issues: string[];
  };
  conversionInfo?: {
    wasMarkdown: boolean;
    conversionApplied: boolean;
  };
}

class AIGenerationService {
  // 使用空字符串，让fetch使用相对路径，通过Vite代理转发
  private baseUrl = '';
  private multiModelService: MultiModelService;

  constructor() {
    // 初始化多模型服务
    this.multiModelService = new MultiModelService({
      openai: {
        apiKey: process.env.REACT_APP_OPENAI_API_KEY || '',
      },
      claude: {
        apiKey: process.env.REACT_APP_CLAUDE_API_KEY || '',
      }
    });
  }

  /**
   * 优化多层Prompt
   */
  optimizePromptLayers(layers: PromptLayers): string {
    return optimizePrompts(layers);
  }

  /**
   * 使用多模型服务生成内容
   */
  async generateWithMultiModel(request: GenerationRequest): Promise<GenerationResponse> {
    try {
      // 简化实现，使用基础生成功能
      return {
        content: '',
        modelId: request.modelType || 'unknown',
        error: 'MultiModel service not implemented'
      };
    } catch (error) {
      console.error('Multi-model generation failed:', error);
      throw error;
    }
  }

  /**
   * 流式生成内容
   */
  async streamWithMultiModel(
    _request: GenerationRequest,
    onChunk: (chunk: { content: string; done: boolean }) => void
  ): Promise<void> {
    try {
      // 简化实现
      onChunk({ content: 'MultiModel streaming not implemented', done: true });
    } catch (error) {
      console.error('Multi-model streaming failed:', error);
      throw error;
    }
  }

  /**
   * 多模型对比生成
   */
  async compareModels(
    prompt: string,
    models: ModelType[],
    maxConcurrency = 3
  ): Promise<ComparisonResult[]> {
    try {
      return await this.multiModelService.compareModels({
        prompt,
        models,
        maxConcurrency
      });
    } catch (error) {
      console.error('Model comparison failed:', error);
      throw error;
    }
  }

  /**
   * 获取可用模型列表
   */
  async getAvailableModels(): Promise<string[]> {
    return [];
  }

  /**
   * 获取模型健康状态
   */
  getModelHealth() {
    return {};
  }

  /**
   * 估算生成成本
   */
  async estimateGenerationCost(_prompt: string, _modelType?: ModelType): Promise<number> {
    return 0;
  }

  /**
   * 使用热点创作专用的LangChain生成（格式化版本）
   */
  async generateHotContentWithFormat(
    hotItemId: string,
    platform: string,
    writingAngle: string = 'news_report',
    userPrompt: string,
    modelName: string = 'gpt-3.5-turbo',
    enableFormat: boolean = true,
    parameters?: any,
    modelConfig?: {
      provider?: string;
      apiKey?: string;
      apiBase?: string;
    }
  ): Promise<GenerationResponse> {
    try {
      let finalPrompt = userPrompt;
      
      // 如果启用格式化，添加格式要求到Prompt中
      if (enableFormat) {
        // 根据写作类型生成对应的格式化Prompt
        const { getFormatPromptByType } = await import('../utils/format-prompt-generator');
        const typeSpecificFormat = getFormatPromptByType(writingAngle);
        
        console.log('=== Prompt分类详情 ===');
        
        // 1. Template Prompt (模板提示词)
        const templatePrompt = "你是一个专业的内容创作助手，专门基于热点话题进行创作。";
        console.log('📝 [1] Template Prompt (模板提示词):');
        console.log('   来源: 预定义模板');
        console.log('   功能: 角色定义、风格控制');
        console.log('   内容:', templatePrompt);
        console.log('');
        
        // 2. System Prompt (系统提示词)
        const systemPrompt = `当前热点信息：
- 标题：华南理工的被撞女生，集齐了所有悲伤点
- 平台：${platform}
- 热度：未知
- 摘要：暂无详细信息

创作要求：
1. 基于提供的热点信息进行创作
2. 保持客观性，避免偏见和不实信息
3. 确保内容的准确性和时效性
4. 遵循新闻伦理和社会责任`;
        console.log('🔧 [2] System Prompt (系统提示词):');
        console.log('   来源: 后端系统生成');
        console.log('   功能: 规范约束、上下文');
        console.log('   内容:', systemPrompt);
        console.log('');
        
        // 3. Smart Prompt (智能提示词)
        console.log('🤖 [3] Smart Prompt (智能提示词):');
        console.log('   来源: AI智能生成');
        console.log('   功能: 任务指导、智能建议');
        console.log('   内容:', typeSpecificFormat.substring(0, 200) + '...');
        console.log('');
        
        // 4. Frontend Prompt (界面提示词)
        const frontendPrompt = `🚨【重要：这是强制性格式要求，必须严格遵守】🚨

你必须按照以下格式输出HTML代码，这不是建议，而是强制要求：

1. 所有标题必须使用HTML标签：
   - 主标题：<h1 style="font-family: 'SimHei', '黑体', sans-serif; font-size: 16pt; font-weight: bold; text-align: left; margin-top: 1em; margin-bottom: 1em; line-height: 1.5;">标题</h1>
   - 副标题：<h2 style="font-family: 'SimHei', '黑体', sans-serif; font-size: 14pt; font-weight: bold; text-align: left; margin-top: 0.5em; margin-bottom: 0.5em; line-height: 1.5;">标题</h2>

2. 所有段落必须使用HTML标签：
   <p style="font-family: 'FangSong_GB2312', '仿宋_GB2312', '仿宋', serif; font-size: 12pt; text-align: justify; text-indent: 2em; line-height: 1.5; margin-bottom: 0.5em;">段落内容</p>

3. 绝对禁止使用：
   - # ## ### 等Markdown标题
   - **粗体** *斜体* 等Markdown语法
   - --- 分隔线
   - 纯文本输出

4. 你的输出必须是完整的HTML代码，可以直接在浏览器中显示。`;
        console.log('🖥️ [4] Frontend Prompt (界面提示词):');
        console.log('   来源: 前端界面设置');
        console.log('   功能: 界面层要求');
        console.log('   内容:', frontendPrompt.substring(0, 200) + '...');
        console.log('');
        
        // 5. User Input (用户输入)
        console.log('👤 [5] User Input (用户输入):');
        console.log('   来源: 用户直接输入');
        console.log('   功能: 个性化要求');
        console.log('   内容:', userPrompt);
        console.log('');
        
        // 合并最终Prompt
        finalPrompt = `${templatePrompt}

${systemPrompt}

现在请按照以下格式要求完成任务：
${userPrompt}

${typeSpecificFormat}

${frontendPrompt}

⚠️ 记住：直接输出HTML代码，不要任何解释文字！`;
        
        // 使用Prompt分析工具进行详细分析
        const analysis = analyzePromptStructure(
          templatePrompt,
          systemPrompt,
          typeSpecificFormat,
          frontendPrompt,
          userPrompt,
          finalPrompt
        );
        
        // 打印详细分析结果
        printPromptAnalysis(analysis);
        
        // 打印结构图表
        console.log(generatePromptChart(analysis));
        
        // 质量评估
        const quality = validatePromptQuality(analysis);
        console.log('=== 📊 Prompt质量评估 ===');
        console.log('质量评分:', quality.score + '/100');
        if (quality.issues.length > 0) {
          console.log('⚠️ 发现问题:');
          quality.issues.forEach(issue => console.log('  -', issue));
        }
        if (quality.suggestions.length > 0) {
          console.log('💡 改进建议:');
          quality.suggestions.forEach(suggestion => console.log('  -', suggestion));
        }
        console.log('');
      }
      
      console.log('=== 最终合并Prompt ===');
      console.log('总长度:', finalPrompt.length, '字符');
      console.log('');
      console.log('📋 完整Prompt内容:');
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      console.log(finalPrompt);
      console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
      console.log('');
      
      const response = await fetch(`${this.baseUrl}/api/v1/hot-content/generate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({
          hot_item_id: hotItemId,
          platform: platform,
          writing_angle: writingAngle,
          user_prompt: finalPrompt, // 使用格式化后的Prompt
          model_name: modelName,
          temperature: parameters?.temperature || 0.7,
          max_tokens: parameters?.maxTokens || 2000,
          stream: false,
          provider: modelConfig?.provider,
          api_key: modelConfig?.apiKey,
          api_base: modelConfig?.apiBase
        })
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      let content = data.content || '';
      
      // 如果启用了格式化，处理内容格式
      if (enableFormat && content) {
        console.log('=== 原始AI输出 ===');
        console.log('内容长度:', content.length);
        console.log('内容预览:', content.substring(0, 300) + '...');
        
        // 智能格式转换
        const conversionResult = smartFormatConversion(content);
        
        console.log('=== 格式转换结果 ===');
        console.log('检测到Markdown:', conversionResult.wasMarkdown);
        console.log('应用了转换:', conversionResult.conversionApplied);
        
        if (conversionResult.conversionApplied) {
          content = cleanupHTML(conversionResult.convertedContent);
          console.log('转换后内容长度:', content.length);
        }
        
        // 验证最终格式
        const validation = validateFormatOutput(content);
        console.log('=== 最终格式验证 ===');
        console.log('格式正确:', validation.isValid);
        if (!validation.isValid) {
          console.warn('格式问题:', validation.issues);
        }
        
        return {
          content,
          usage: data.usage,
          modelId: modelName,
          formatValidation: validation,
          conversionInfo: {
            wasMarkdown: conversionResult.wasMarkdown,
            conversionApplied: conversionResult.conversionApplied
          }
        };
      }
      
      return {
        content,
        usage: data.usage,
        modelId: modelName
      };
    } catch (error) {
      console.error('优化版热点生成失败:', error);
      return {
        content: '',
        modelId: modelName,
        error: error instanceof Error ? error.message : '生成失败'
      };
    }
  }

  /**
   * 使用热点创作专用的LangChain生成
   */
  async generateHotContent(
    hotItemId: string,
    platform: string,
    writingAngle: string = 'news_report',
    userPrompt?: string,
    modelName: string = 'gpt-3.5-turbo',
    parameters?: any,
    modelConfig?: {
      provider?: string;
      apiKey?: string;
      apiBase?: string;
    }
  ): Promise<GenerationResponse> {
    try {
      const response = await fetch(`${this.baseUrl}/api/v1/hot-content/generate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({
          hot_item_id: hotItemId,
          platform: platform,
          writing_angle: writingAngle,
          user_prompt: userPrompt,
          model_name: modelName,
          temperature: parameters?.temperature || 0.7,
          max_tokens: parameters?.maxTokens || 2000,
          stream: false,
          // 添加模型配置
          provider: modelConfig?.provider,
          api_key: modelConfig?.apiKey,
          api_base: modelConfig?.apiBase
        })
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.detail || `HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      
      return {
        content: data.content,
        usage: data.usage ? {
          promptTokens: data.usage.prompt_tokens,
          completionTokens: data.usage.completion_tokens,
          totalTokens: data.usage.total_tokens
        } : undefined,
        modelId: data.generation_metadata.model_name
      };
    } catch (error) {
      console.error('Hot content generation failed:', error);
      throw error;
    }
  }

  /**
   * 流式热点内容生成
   */
  async generateHotContentStream(
    hotItemId: string,
    platform: string,
    writingAngle: string = 'news_report',
    userPrompt?: string,
    modelName: string = 'gpt-3.5-turbo',
    parameters?: any,
    onChunk?: (chunk: string) => void,
    onComplete?: (result: any) => void,
    onError?: (error: Error) => void
  ): Promise<void> {
    try {
      console.log('=== 开始流式生成请求 ===');
      console.log('请求URL:', `${this.baseUrl}/api/v1/hot-content/generate-stream`);
      console.log('请求参数:', {
        hot_item_id: hotItemId,
        platform: platform,
        writing_angle: writingAngle,
        user_prompt: userPrompt,
        model_name: modelName,
        temperature: parameters?.temperature || 0.7,
        max_tokens: parameters?.maxTokens || 2000,
        stream: true
      });

      const response = await fetch(`${this.baseUrl}/api/v1/hot-content/generate-stream`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getAuthToken()}`
        },
        body: JSON.stringify({
          hot_item_id: hotItemId,
          platform: platform,
          writing_angle: writingAngle,
          user_prompt: userPrompt,
          model_name: modelName,
          temperature: parameters?.temperature || 0.7,
          max_tokens: parameters?.maxTokens || 2000,
          stream: true
        })
      });

      console.log('响应状态:', response.status, response.statusText);

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        console.error('请求失败:', errorData);
        throw new Error(errorData.detail || `HTTP ${response.status}: ${response.statusText}`);
      }

      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('Response body is not readable');
      }

      const decoder = new TextDecoder();
      let buffer = '';
      let chunkCount = 0;

      try {
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            console.log('流式读取完成，共接收', chunkCount, '个数据块');
            break;
          }

          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split('\n');
          buffer = lines.pop() || '';

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6);
              console.log('收到SSE数据:', data.substring(0, 100) + (data.length > 100 ? '...' : ''));

              if (data === '[DONE]') {
                console.log('收到结束标记');
                return;
              }

              try {
                const parsed = JSON.parse(data);
                console.log('解析后的数据类型:', parsed.type);

                if (parsed.error) {
                  console.error('服务器返回错误:', parsed.error);
                  onError?.(new Error(parsed.error));
                  return;
                }

                if (parsed.type === 'content' && parsed.content) {
                  chunkCount++;
                  console.log(`调用onChunk回调 (第${chunkCount}次)，内容长度:`, parsed.content.length);
                  onChunk?.(parsed.content);
                } else if (parsed.type === 'completion' && parsed.finished) {
                  console.log('生成完成，调用onComplete回调');
                  onComplete?.(parsed.metadata);
                }
              } catch (e) {
                console.warn('Failed to parse SSE data:', data, e);
              }
            }
          }
        }
      } finally {
        reader.releaseLock();
      }
    } catch (error) {
      console.error('Hot content streaming failed:', error);
      onError?.(error as Error);
    }
  }

  /**
   * 获取写作角度列表
   */
  async getWritingAngles(): Promise<{writing_angles: string[], descriptions: Record<string, string>}> {
    try {
      const response = await fetch(`${this.baseUrl}/api/v1/hot-content/writing-angles`, {
        headers: {
          'Authorization': `Bearer ${this.getAuthToken()}`
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('Failed to get writing angles:', error);
      throw error;
    }
  }

  /**
   * 获取相关热点
   */
  async getRelatedHotItems(itemId: string, platform: string, limit: number = 5): Promise<any[]> {
    try {
      const response = await fetch(`${this.baseUrl}/api/v1/hot-content/related-items/${itemId}?platform=${platform}&limit=${limit}`, {
        headers: {
          'Authorization': `Bearer ${this.getAuthToken()}`
        }
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      return data.related_items || [];
    } catch (error) {
      console.error('Failed to get related items:', error);
      throw error;
    }
  }

  /**
   * 获取认证token
   */
  private getAuthToken(): string {
    return localStorage.getItem('access_token') || '';
  }

  /**
   * 使用选中的模型配置生成内容
   */
  async generateWithConfig(
    modelConfig: any,  // 模型配置对象
    prompt: string,
    parameters: any = {}
  ): Promise<GenerationResponse> {
    try {
      // AI创作使用热点内容生成API端点，使用通用参数
      
      const response = await fetch('/api/v1/hot-content/generate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          hot_item_id: 'general-content', // AI创作使用通用热点ID
          platform: 'general',
          writing_angle: 'creative_writing',
          user_prompt: prompt,
          model_name: modelConfig.modelName || modelConfig.model,
          temperature: parameters.temperature || 0.7,
          max_tokens: parameters.maxTokens || 2000,
          stream: false,
          provider: modelConfig.provider,
          api_key: modelConfig.apiKey,
          api_base: modelConfig.baseUrl || modelConfig.apiBase
        })
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`生成失败: ${response.status} - ${errorText}`);
      }

      const result = await response.json();
      return {
        content: result.content || '',
        usage: result.usage ? {
          promptTokens: result.usage.prompt_tokens,
          completionTokens: result.usage.completion_tokens,
          totalTokens: result.usage.total_tokens
        } : undefined,
        modelId: modelConfig.id
      };
      
      // 根据不同的模型提供商，构建不同的请求
      // const requestBody = this.buildRequestBody(modelConfig, prompt, parameters);
      
    } catch (error: any) {
      console.error('Generation failed:', error);
      throw error;
    }
  }





  /**
   * 测试模型连接
   */
  async testConnection(modelConfig: any): Promise<boolean> {
    try {
      const response = await this.generateWithConfig(
        modelConfig,
        'Hello, please respond with "OK" if you can hear me.',
        { maxTokens: 10 }
      );
      return !!response.content;
    } catch (error) {
      console.error('Connection test failed:', error);
      return false;
    }
  }
}

export const aiGenerationService = new AIGenerationService();